<template>
	<div class="deployClass" style="margin-top:10px;">
		<Row style="margin-bottom:10px;">
			  <Select filterable v-model="exp" style="width:150px;margin-right:15px" v-if="environInfo.expList.length > 1" @on-change="getEnvironData">
		        <Option v-for="item in environInfo.expList" :value="JSON.stringify(item)" :key="item.expid" :title="item.expName">{{ item.expName }}</Option>
		    </Select>
		    <Input v-model.trim="user" style="width:180px;margin-right:15px" placeholder="请输入昵称搜索" clearable></Input>
		    <div style="float:right;">
		    	<!--<Tag type="border" color="success">在线人数： {{onlineNum}}</Tag>-->
		    	<!--<Tag type="border" color="primary">接入人数： {{loginNum}}</Tag>-->
		    	<Button type="info" size="small" v-if="step == 0" :disabled="disabledBatchDeploy || batchDeployLoading || disbledAllBtn" @click="batchDeployClass">批量部署</Button>
			    <Poptip
		          confirm
		          title="确认销毁选中的环境？"
		          @on-ok="batchExperimentDestroy"
		          transfer
		          word-wrap width="200"
		          v-else>
		          <Button type="error" size="small" :disabled="disabledBatchDestroy || batchDestroyLoading || disbledAllBtn">批量销毁</Button>
		        </Poptip>
		    </div>
		</Row>
		<div style="margin-bottom:10px" v-if="selectOpUsers.length > 0">已选择：<Tag v-for="user in selectOpUsers" :key="user.userId" color="blue">{{user.userName}}</Tag></div>
	   <Table border :columns="environCol" :row-class-name="rowClassName" :data="showEnvironList"
	   	@on-select="addDeployUser" @on-select-all = "addDeployUser"
	   	@on-select-cancel = "removeDeployUser" @on-select-all-cancel="removeDeployUser"></Table>
	   <Page :total="environList.length" :page-size="10" show-elevator :page="environPage" show-total 
		  style="text-align:center;margin-top:10px;" @on-change="changeEnvironPage"/>
	   <!--  虚拟机列表，提供接入虚拟机-->
	  <Modal
	    v-model="vmsModal"
	    :mask-closable="false"
	    title="虚拟机列表"
	    width="90">
	    <Table border :columns="vmsCol" :data="vmsRow(vmsList)" v-if="vmsModal" :max-height="400"></Table>
	  </Modal>
	  <!--<Modal
        v-model="vmOpModal.show"
        title="操作虚拟机"
        width="380"
        @on-cancel="cancel"
        @on-ok="vmSwitchTypeOp"
      >
        <div style="font-size:14px;">
            {{vmOpModal.content}}
        </div>
    </Modal>-->
	</div>
</template>

<script>
	import encryption from '@/libs/encryption.js'
	import {getCompanyUsersInfo} from '@/api/users'
	import {deployClass,getClassUsers,updateClassStatus,batchExperimentDestroy,queryCheckScreenStatus} from '@/api/selfStudy/class.js'
	import {getRecord} from '@/api/selfStudy/access.js'
	import {getstatusbyprjid} from '@/api/drill'
	import {courseDetail,expEnv,getVms,experimentDestroy} from '@/api/selfStudy/courseExp.js'
	import {queryVmStatus,opVms,rebuildVm,rebootVm} from '@/api/remote.js'
	import {getmemdata} from '@/api/drill_compete'
	import vmsType from './vmsType'
	import { mapState } from 'vuex'

	export default {
		name: 'deployClass',
		props:['show','environInfo','classInfo','step','disbledAllBtn','courseStatus'],
		components:{vmsType},
		data() {
			let September = sessionStorage.getItem('November')
            September = JSON.parse(encryption.SelfUseDecrypt(September))
			return {
				USER_ID:September.userId,
				USER_Name:September.nickname,
				user:'',
//				classUsers:[],
//				allExpList:[],
				curExpId:'',
				//环境列表
				environList:[], //环境列表数据
				environTime:{},//环境列表定时器
				///index:0,
				//虚拟机列表
				vmsList:[],
				vmsModal:false, //虚拟机列表modal
				vmStatusTimeout:{}, //虚拟机状态定时器
				timeout:{},//虚拟机资源监控定时器
				//当前课件数据
				exp:'',
				curExp:'',
				curExpId:'',
				// 计算index
				environCol:[
					{
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
					{
                        title: '序号',
                        align: 'center',
                        width:65,
                        render:(h,params) => {
                        	let index = (this.environPage-1)*10 + params.row._index + 1
                        	return h('span',index)
                        }
                    },
					{
                        title: '昵称',
                        key: 'userName',
                        align: 'center'
                    },
                    {
        				title:'类型',
        				key:'type',
        				tooltip:true,
        				align: 'center',
        				render:(h,params) => {
        					return h('span',params.row.type == 'T' ? '教师' :'学生')
        				}
        			},
                    {
						title: '课件名',
						key: 'expName',
						align: 'center',
						tooltip: true,
						render:(h,params) => {
							if(params.row.projectId){
								return h('Tooltip',{
									props:{
										transfer:true,
										content:'点击进入拓扑图'
									}
								},[
								   h('a',{
		                        		on:{
		                        			'click':() => {
		                        				this.gotoTopo(params.row);
		                        			}
		                        		}
		                        	},params.row.expName)
								])
							}else{
								return h('span',params.row.expName)
							}
                        },
					},
					{
						title: '部署状态',
						key: 'deployStatus',
						align: 'center',
						render:(h,params) => {
							return h('div',[
								h('Tag',{
	                        		props:{
	                        			color:this.$options.filters.statusFilter(params.row.deployStatus,'color')
	                        		}
	                        	},this.$options.filters.statusFilter(params.row.deployStatus,'text')),
	                        	h('Poptip',{
	                        		props:{
	                        			trigger:"hover", 
	                        			width:"300",
	                        			content:params.row.errorMessage, 
	                        			wordWrap:true,
	                        			transfer:true
	                        		},
	                        		style:{
	                        			display:params.row.errorMessage ? '':'none'
	                        		}
	                        	},[
	                        		h('Icon',{
	                        			props:{
	                        				type:'ios-help-circle',
	                        				color:'rgb(203, 2, 54)',
	                        				size:16
	                        			},
	                        			style:{
	                        				cursor:'pointer'
	                        		    }
	                        		})
	                        	])
							])
                        },
                        tooltip: true
					},
					{
                    	title:'是否在线',
                    	render:(h,params) => {
                        	return h('Tag', {
                        		props:{
                        			type:'border',
                        			color:params.row.user.online ? 'success' :''
                        		}
                        	},params.row.user.online ? '在线' : '离线')
                        },
                        align: 'center',
                        tooltip: true
                    },
                    {
                    	title:'是否接入',
                    	render:(h,params) => {
                    		let recordCol = [
                    			{
                    				title:'虚拟机名称',
                    				key:'name',
                    				ellipsis:true,
                    				tooltip:true
                    			},
                    			{
                    				title:'昵称',
                    				key:'userName',
                    				tooltip:true
                    			},
                    			{
                    				title:'实例名称',
                    				key:'instanceName',
                    				tooltip:true
                    			},
                    			{
                    				title:'接入方式',
                    				key:'protocol',
                    				tooltip:true
                    			},
                    			{
                    				title:'登录时间',
                    				key:'connectTime',
                    				tooltip:true
                    			}
                    		];
                    		// if(params.row.records){
                    		// 	var record = params.row.records.filter(record => record.status == 'connected')
                    		// }
                    		if(!params.row.login){
                    			return h('span',params.row.loginText);
                    		}else{
                    			if(this.classInfo.type == '2' || (this.classInfo.type == '3' && this.classInfo.status == '1')){
                    				return h('a',params.row.loginText);
                    			}else{
                    				return h('Poptip',{
		                    			props:{
		                    				width:600,
		                    				trigger:'hover',
		                    				transfer:true
		                    			},
		                    			on:{
		                    				'on-popper-show':() => {
		                    					this.getAccessRecord(params.row)
		                    				}
		                    			}
		                    		},[
		                    			h('a',params.row.loginText),
		                    			h('div',{
		                    				 slot:'content'
		                    			},[
		                    				h('Table',{
		                    					props:{
		                    						data:params.row.records,
		                    						columns:recordCol,
		                    						height:300
		                    					}
		                    				})
		                    			])
		                    		])
                    			}
                    		}
                        },
                        align: 'center'
                    },
                    {
					    title:'操作',
					    width:200,
					    render:(h,params) => {
					    	return h('div', [
								h('Button', {
									props: {
										type: 'info',
										size: 'small',
										disabled:this.disDeploy(params.row)
									},
									style: {
										marginRight: '5px',
										display:this.step == 0 ? 'inline-block':'none'
									},
									on: {
										click: () => {
//											if(this.curClass.type == '1' || this.curClass.type == '3' ){
//												this.deployClass([params.row.user.id]);
//											}else{
//												this.experimentIdlist = [params.row.ecid];
//												this.deployClass([params.row.userId])
//											}
											this.deployClass(params.row);
										}
									}
								}, '部署'),
								h('Button', {
									props: {
										type: 'error',
										size: 'small',
										disabled:!this.disbledAllBtn && (params.row.deployStatus == 3 && !params.row.disDestory) ? false : true
									},
									style: {
										marginRight: '5px',
										display:this.step != 0 ? 'inline-block':'none'
									},
									on: {
										click: () => {
											this.doExperimentDestroy(params.row);
										}
									}
								}, '销毁'),
								h('Button', {
									props: {
										type: 'info',
										size: 'small',
										disabled:(params.row.deployStatus == 3 && params.row.type == 'T') || (params.row.deployStatus == 3 && params.row.type == 'S' && params.row.loginText == '已接入虚拟机') ? false : true
									},
									style: {
										marginRight: '5px',
										display:this.step == 1 ||  (this.step == 0 && params.row.type == 'T') ? 'inline-block':'none'
									},
									on: {
										click: () => {
											//console.log(this.classInfo)
 											if(params.row.type == 'S' && params.row.loginText == '已接入虚拟机' && (this.classInfo.type == '1' || (this.classInfo.type == '3' && this.classInfo.status == '0'))){
												const { href } = this.$router.resolve({
								                	path:'/testScreen',
									                query:{
									                    prjId:params.row.projectId,
														ecId:params.row.expid,
														userId:params.row.userId,
														classId:this.classInfo.id
									                }
									            });
									            window.openTrain(href, '_blank')
											}else{
												this.vmsModal = true;
	//											if(this.classInfo.type == '2'){
	//												this.curExpId = params.row.ecid;
	//											}
												this.curExpId = params.row.expid;
												this.curProjectId = params.row.projectId;
												this.getVms(params.row.projectId)
	//											this.enterEnviron(params.row.projectId);
											}
										}
									}
								}, (params.row.type == 'S' && (this.classInfo.type == '1' || (this.classInfo.type == '3' && this.classInfo.status == '0'))) ? '查看实时屏幕' : '进入环境'),//学生、实操模式、教学模式的实操状态查看实时屏幕
//								h('Button', {
//									props: {
//										type: 'info',
//										size: 'small',
//										disabled:params.row.deployStatus == 3 ? false : true
//									},
//									style: {
//										marginRight: '5px',
////										display:this.step == 3  ? 'inline-block':'none'
//									},
//									on: {
//										click: () => {
//
//										}
//									}
//								}, '答题记录'),
//								h('Poptip',{
//	                    			props:{
//	                    				width:600,
//	                    				trigger:'hover',
//	                    				transfer:true
//	                    			},
//	                    			on:{
//	                    				'on-popper-show':() => {
//	                    					this.getVms(params.row.projectId)
//	                    				}
//	                    			}
//	                    		},[
//	                                h('Button', {
//										props: {
//											type: 'info',
//											size: 'small',
//											disabled:params.row.deployStatus == 3 ? false : true
//										},
//										style: {
//											marginRight: '5px'
//										},
//										on: {
//											click: () => {
////												this.enterEnviron(params.row.projectId);
//											}
//										}
//									}, '进入环境'),
//	                    			h('div',{
//	                    				 slot:'content'
//	                    			},[
//	                    				h('Table',{
//	                    					props:{
//	                    						data:this.vmsList,
//	                    						columns:vmsCol,
////	                    						height:300
//	                    					}
//	                    				})
//	                    			])
//	                    		])
							])
					    }
					}
				],
				vmsCol:[
			        {
			          type:'index',
			          width:60,
			          align:'center'
			        },
			        {
			          title:'虚拟机名称',
			          key:'name',
			          align:'center',
			        },
			//        {
			//          title:this.$t('VmType'),
			//          key:'vmType',
			//          align:'center',
			//        },
			        {
			          title:'类型',
			          key:'vzType',
			          align:'center',
			        },
//			        {
//			          title:this.$t('projectName'),
//			          key:'projectName',
//			          align:'center',
//			        },
			        // {
			        //   title:'实例名称',
			        //   key:'instance',
			        //   align:'center',
			        // },
			        {
			          title:'状态',
			          key:'status',
			          align:'center',
			        },
//			        {
//			          title:this.$t('HostIp'),
//			          key:'hostIp',
//			          align:'center',
//			        },
			        {
			          title:'主机名称',
			          key:'host',
			          align:'center',
			        },
			        {
			          title:'系统类型',
			          key:'sysType',
			          align:'center',
			        },
//			        {
//			          title:this.$t('OSId'),
//			          key:'osId',
//			          align:'center',
//			        },
                    {
                    	title:'CPU总量',
                    	key:'cpu',
			            align:'center',
                    },
			        {
			          title:"磁盘总量(GB)",
			          key:'disk',
			          align:'center',
			        },
			        {
			          title:"内存总量(MB)",
			          key:'ram',
			          align:'center',
			        },
					{
			          title:"CPU使用率(%)",
			          key:'cpuVal',
			          align:'center',
			          render:(h,params) => {
			          	return h('Tag',{
			          		props:{
			          			color:'primary'
			          		}
			          	},params.row.cpuVal || '-')
			          }
			        },
			        {
			          title:"磁盘使用率(%)",
			          key:'diskVal',
			          align:'center',
			          render:(h,params) => {
			          	return h('Tag',{
			          		props:{
			          			color:'primary'
			          		}
			          	},params.row.diskVal || '-')
			          }
			        },
			        {
			          title:"内存使用率(%)",
			          key:'memVal',
			          align:'center',
			          render:(h,params) => {
			          	return h('Tag',{
			          		props:{
			          			color:'primary'
			          		}
			          	},params.row.memVal || '-')
			          }
			        },
			        {
			          title:'用户名',
			          key:'username',
			          align:'center',
			        },
			        {
			          title:'密码',
			          key:'password',
			          align:'center',
			        },
			        {
			          title:'更新时间',
			          key:'updated',
			          align:'center',
			        },
			        {
			          title:'操作',
			          key:'action',
			          align:'center',
			          width:300,
			          render: (h, params) => {
			          	let action = '';
			          	let text = '';
			          	let type = '';
			          	let disabled = false;
			          	if(!params.row.status){
			          		return;
			          	}
			          	if(params.row.status == 'ACTIVE' || params.row.status == 'running'){
		            		action = "os-stop";
		            		text = "关机";
		            		type  = "primary"
		            	}else if(params.row.status == 'DOWN' || params.row.status == 'Stopped' || params.row.status == 'SHUTOFF'){
		            		action = "start";
		            		text = "开机";
		            		type  = "primary"
		            	}else{
		            		text = "开机";
		            		type  = "primary";
		            		disabled = true;
		            	}
			            return h('div',[
			                h('div',{
			                	attrs: {
							      id:'selectBtn'
							    },
			                },[
			                	h('Button', {
									props: {
										type: type,
										disabled:disabled
	//									size: 'small'
									},
									style: {
										borderRadius:'4px 0 0 4px'
									},
									on: {
										click: () => {
											this.opVm(params.row.id,action);
										}
									}
								}, text),
								h('Select',{
									props:{
										'placeholder':'',
										transfer:true
									},
									style:{
										width:'20px'
									},
									on:{
										'on-select':(val) => {
											if(val == 'reboot-hard'){
												this.rebootVm(params.row.id,'HARD');
											}else if(val == 'reboot-soft'){
												this.rebootVm(params.row.id,'SOFT');
											}else if(val == 'rebuild'){
												this.rebuildVm(params.row.id);
											}
										}
									}
								},[
									h('Option',{
										props:{
											value:'reboot-soft'
										}
									},'软重启'),
									h('Option',{
										props:{
											value:'reboot-hard'
										}
									},'硬重启'),
									h('Option',{
										props:{
											value:'rebuild'
										}
									},'重置')
								]),
//								h('Button', {
//									props: {
//										type: 'primary',
//	//									size: 'small'
//									},
//									style: {
//										marginRight: '5px'
//									},
//									on: {
//										click: () => {
//											this.rebootVm(params.row.id);
//										}
//									}
//								}, '重启'),
//								h('Button', {
//									props: {
//										type: 'primary',
//	//									size: 'small'
//									},
//									style: {
//										marginRight: '5px'
//									},
//									on: {
//										click: () => {
//											this.rebuildVm(params.row.id);
//										}
//									}
//								}, '重置'),
			                ]),
			            	h(vmsType, {
				              props: {
				                row: params.row,
				                ecid:this.curExpId,
				                classId:this.classInfo.id
				              },
				              style:{
				              	display:'inline-block'
				              }
				            })
			            ])
			          }
			        },
			      ],
			      vmsRow(val){
			        let data = [];
			        for(let i=0;i<val.length;i++){
			          data.push({
			            name:val[i]['name'],
			            vmType:val[i]['vmType'],
			            vzType:val[i]['vzType'],
			            projectId:val[i]['projectId'],
			            projectName:val[i]['projectName'],
			            osId:val[i]['osId'],
			            hostIp:val[i]['hostIp'],
			            host:val[i]['host'],
			            sysType:val[i]['sysType'],
			            instance:val[i]['instanceName'],
			            status:val[i]['status'],
			            updated:val[i]['updated'],
			            cpu:val[i]['cpu'],
			            disk:val[i]['disk'],
			            ram:val[i]['ram'],
			            diskVal:val[i]['diskVal'],
			            memVal:val[i]['memVal'],
			            cpuVal:val[i]['cpuVal'],
			            id:val[i]['id'],
			            accesses:val[i]['accesses'],
			            username:val[i]['accesses'][0].username,
			            password:val[i]['accesses'][0].password
			          })
			        }
			        return data
			      },
			      environPage:1,
			      //批量部署，批量销毁控制
			      batchDestroyLoading:false,
			      batchDeployLoading:false,
			      //选择的操作用户
				  selectOpUsers:[],
//			      vmOpModal:{
//		            loading:true,
//		            show:false,
//		            content:''
//		          }
			}
		},
		mounted() {
			if(this.environInfo && this.classInfo){
				this.getEnvironData();
			}
			if (this.cloudType === 'h3c') {
				let index = this.vmsCol.findIndex(item => item.key === 'action')
				if (index !== -1) {
					this.vmsCol.splice(index, 1, {
						title:'操作',
						key:'action',
						align:'center',
						width:300,
						render: (h, params) => {
							let action = '';
							let text = '';
							let type = '';
							let disabled = false;
							if(!params.row.status){
								return;
							}
							if(params.row.status == 'ACTIVE' || params.row.status == 'running'){
								action = "os-stop";
								text = "关机";
								type  = "primary"
							}else if(params.row.status == 'DOWN' || params.row.status == 'Stopped' || params.row.status == 'SHUTOFF'){
								action = "start";
								text = "开机";
								type  = "primary"
							}else{
								text = "开机";
								type  = "primary";
								disabled = true;
							}
							return h('div',[
								h('div',{
									attrs: {
									id:'selectBtn'
									},
								},[
									h('Button', {
										props: {
											type: type,
											disabled:disabled
		//									size: 'small'
										},
										style: {
											borderRadius:'4px 0 0 4px'
										},
										on: {
											click: () => {
												this.opVm(params.row.id,action);
											}
										}
									}, text),
									h('Select',{
										props:{
											'placeholder':'',
											transfer:true
										},
										style:{
											width:'20px'
										},
										on:{
											'on-select':(val) => {
												if(val == 'reboot-hard'){
													this.rebootVm(params.row.id,'HARD');
												}else if(val == 'reboot-soft'){
													this.rebootVm(params.row.id,'SOFT');
												}else if(val == 'rebuild'){
													this.rebuildVm(params.row.id);
												}
											}
										}
									},[
										h('Option',{
											props:{
												value:'reboot-soft'
											}
										},'软重启'),
										h('Option',{
											props:{
												value:'reboot-hard'
											}
										},'硬重启')
									]),
								]),
								h(vmsType, {
								props: {
									row: params.row,
									ecid:this.curExpId,
									classId:this.classInfo.id
								},
								style:{
									display:'inline-block'
								}
								})
							])
						}
					})
				}
			}
		},
		beforeDestroy(){
			this.clearAll();
		},
		computed:{
			...mapState(['cloudType']),
			'onlineNum':function(){
				return this.environList.filter(env => env.user.online).length || 0;
			},
			'loginNum':function(){
				return this.environList.filter(env => env.login).length || 0;
		    },
		    'showEnvironList':function(){
		    	let environList = [];
		    	if(this.user){
		    		environList = this.environList.filter(environ => environ.userName.indexOf(this.user) != -1).slice((this.environPage-1)*10,this.environPage*10);
		    	}else{
		    		environList = this.environList.slice((this.environPage-1)*10,this.environPage*10);
		    	}
		    	let userIds = this.selectOpUsers.map(user => user.userId);
	    		environList.forEach(environ => {
	    			if(userIds.includes(environ.userId)){
	    				environ._checked = true;
	    			}else{
	    				environ._checked = false;
	    			}
	    			environ._disabled = this.disSelect(environ);
	    		})
	    		return environList;
		    },
		    'disabledBatchDeploy':function(){
		    	return this.selectOpUsers.length == 0//this.environList.every(environ => environ.deployStatus == 3) || this.classInfo.type == '2';
		    },
		    'disabledBatchDestroy':function(){
		    	return this.selectOpUsers.length == 0//this.showEnvironList.every(environ => environ.deployStatus == 10) || this.classInfo.type == '2';
		    },
		},
		watch:{
			show:function(val){
				if(val && this.environInfo){
//					this.getEnvironData();
				}
			},
			classInfo:{
				deep:true,
				handler:function(val,oldVal){
					let _this = this;
					this.intervalFunction();
				}
			},
			environInfo:{
				deep:true,
				handler:function(val,oldVal){
					let _this = this;
					if(val != oldVal){
						this.getEnvironData();
						this.intervalFunction();
					}
				}
			},
			step:function(val,oldVal){
				if(val != oldVal){

				}
			},
			showEnvironList:function(val,oldval){
				if(JSON.stringify(val) == JSON.stringify(oldval)){
					return
				}
				this.intervalFunction();
			}
		},
		filters: {
			typeFilter(val) {
				let str = '';
				switch (val) {
					case '1':
						str = '实操模式';
						break;
					case '2':
						str = '讲课模式';
						break;
					case '2':
						str = '教学模式';
						break;
				}
				return str;
			},
			//0-新建 3-部署成功 6-部署失败 8-删除失败9-部署中,10没有部署
			statusFilter(val,type){
				let str = '';
			    let color = '';
				switch (val) {
					case 0:
						str = '未部署';
						color='#888';
						break;
					case 3:
						str = '部署成功';
						color='#06b649';
						break;
					case 6:
						str = '部署失败';
						color='#ff4242';
						break;
					case 8:
						str = '删除失败';
						color='#fa9901';
						break;
					case 9:
						str = '部署中';
						color='#06b649';
						break;
					case 10:
						str = '未部署';
						color='#888';
						break;
					case 14:
						str = '清空部署失败';
						color='#ff8244';
						break;
					default:
					    str = '未部署';
					    color='#888';
				}
				if(type == 'text'){
					return str;
				}else{
					return color;
				}
            },
		},
		methods: {
			getEnvironData(exp){
				let environInfo;
				if(this.environInfo && this.environInfo.stuList.length > 0 && this.environInfo.expList.length > 0){
					environInfo = JSON.parse(JSON.stringify(this.environInfo));
				}else{
					return;
				}
				this.environList = [];
				//查询教学环境部署状态
				let teacher = {
					userId:this.classInfo.teacherId,//、this.USER_ID,
					userName:this.classInfo.teacherName,
					type:'T',
					user:{
						online:true
					}
				}
//				console.log(this.classInfo);
				if(this.classInfo.type == '3' || this.classInfo.type == '2'){ //教学模式，学生和老师的环境都要部署
					environInfo.stuList.unshift(teacher);
				}
//				else if(this.classInfo.type == '2'){ //讲课模式，部署教师的课件环境
//					environInfo.stuList = [teacher];
//				}
				if(!exp){
					this.exp = JSON.stringify(environInfo.expList[0]);
					this.curExp =  exp || JSON.stringify(environInfo.expList[0]);
				}else{
					this.clearAll();
					this.curExp = exp;
				}
				[JSON.parse(this.curExp)].forEach(exp => {
					environInfo.stuList.forEach(stu => {
						if(!stu.type){
							this.$set(stu,'type','S');
						}
						let environ = Object.assign(stu,exp);
						environ.courseId = this.environInfo.courseId;
						environ.classId = this.environInfo.classId;
						environ.login = false;
						environ.loginText = '未接入虚拟机';
//						this.getDeployStatus(environ);
						this.environList.push(environ);
					})
				})
				let tEnv = this.environList.shift();
				this.environList.sort((a,b) => {
					return a.userName.localeCompare(b.userName);
				})
				this.environList.unshift(tEnv);
			},
//			getClassUsers(){
//				return new Promise((resolve, reject) => {
//					getClassUsers({classId:this.curClass.id}).then(data => {
//						if(data.code == 1){
//							this.classUsers = data.attribute.stuIdList;
//							// resolve(data.attribute.stuIdList);
//						}else{
//							// reject();
//						}
//					})
//				})
//			},
			clearAll(){
				if(this.environTime){
					Object.values(this.environTime).forEach(timer=> {
						clearTimeout(timer)
					})
					this.environTime = {};
				}
//				[JSON.parse(this.curExp)].forEach(exp => {
//					this.environInfo.stuList.forEach(stu => {
//						let symbol1 = exp.expid + '-' + stu.userId;
//						clearInterval(this.environTime[symbol1])
//						this.environTime = {};
//					})
//				})
			},
			deployClass(environInfo){
				this.$set(environInfo,'disDeploy',true)
				let params = {
					userid:[environInfo.userId],
					ecid:[environInfo.expid]
				}
				deployClass(this.classInfo.id,this.classInfo.type,this.environInfo.classNumberId,params).then(data => {
					if(data.code == 1){
						this.$Message.info('操作成功')
						this.$set(environInfo,'disDeploy',false)
						this.getDeployStatus(environInfo);
					}else{
						this.$set(environInfo,'disDeploy',false)
						this.$Message.warning(data.message)
					}
				}).catch(error => {
					this.$set(environInfo,'disDeploy',false)
				})
			},
			batchDeployClass(){
				this.batchDeployLoading = true;
				const msg = this.$Message.loading({
                    content: '请求中...',
                    duration: 0
                });
				let expId = JSON.parse(this.curExp).expid;
				let params = {
					userid:this.selectOpUsers.map(env => env.userId), //filter(env => env.deployStatus == 6 || env.deployStatus == 10 || !env.deployStatus)
					ecid:[expId]
				}
				deployClass(this.classInfo.id,this.classInfo.type,this.environInfo.classNumberId,params).then(data => {
					if(data.code == 1){
						setTimeout(msg,20);
					  	setTimeout(() => {
					  		this.$Message.success('操作成功');
					  	},20)
						this.batchDeployLoading = false;
						this.selectOpUsers = [];
						this.showEnvironList.forEach(environ => {
			    			this.getDeployStatus(environ);
			    		})
					}else{
						setTimeout(msg,20);
						setTimeout(() => {
					  		this.$Message.error(data.message);
					  	},20)
						this.batchDeployLoading = false;
					}
				}).catch(error => {
					setTimeout(msg,20);
					setTimeout(() => {
				  		this.$Message.error('请求失败');
				  	},20)
					this.batchDeployLoading = false;
				})
			},
			getAccessRecord(user){
				let params = {
					projectId:user.projectId,
					userId:user.userId,
					page:this.curAccessPage,
					rows:this.curAccessRows,
					status:'connected'
				}
				let symbol1 = user.expid + '-' + user.userId;
				if(user.projectId){
					getRecord(params).then(data => {
						if(data.code == 1){
//							let record = data.data.list.filter(record => record.status == 'connected');
							let record = data.data.items;
							if(record.length > 0){
								this.$set(user,'login',true)
								this.$set(user,'loginText','已接入虚拟机');
								this.$set(user,'records',record)
							}else{
								this.$set(user,'login',false)
								this.$set(user,'loginText','未接入虚拟机');
								this.$set(user,'records',record)
							}
							if(user.type == 'T'){
								this.$emit('getTeacherConnected',record)
							}
						}else{
							this.$set(user,'login',false)
							this.$set(user,'records',[])
							this.$set(user,'loginText','未接入虚拟机');
							this.$Message.warning(data.message)
						}
					})
				}else{
					this.$set(user,'login',false)
					this.$set(user,'records',[])
				}
			},
			queryCheckScreenStatus(user){
				let params = {
					classId:user.classId,
					classNumberId:this.environInfo.classNumberId,
					ecId:user.expid,
					userId:user.userId,
					isGetScreen:1
				}
				queryCheckScreenStatus(params).then((data) => {
					if(data.code == 1){
						let record = data.attribute.data;
						if(record.length > 0){
							this.$set(user,'login',true);
							this.$set(user,'loginText','已接入投屏');
							this.$set(user,'records',[])
						}else{
							this.$set(user,'login',false);
							this.$set(user,'loginText','未接入投屏');
							this.$set(user,'records',[])
						}
					}else{
						this.$Message.warning(data.message);
						this.$set(user,'login',false);
						this.$set(user,'loginText','未接入投屏');
						this.$set(user,'records',[])
					}
				})
			},
			getCompanyUsersInfo(user){
				getCompanyUsersInfo(user.userId).then(data => {
					if(data.code == 1){
						this.$set(user.user,'online',data.data.online)
					}
				})
			},
			getDeployStatus(environ){
				let path = {
					eid:environ.expid,
					uid:environ.userId
				}
				let params = {
					ccid:environ.courseId,
					assignFlag:'T',
					classId:environ.classId,
					classNumberId:this.environInfo.classNumberId
				}
				let symbol1 = environ.expid + '-' + environ.userId;
				expEnv(path,params).then(data => {
					//获取当前用户信息
					let projectId  = data.attribute.data.instanceid;
					let vmStatus  = data.attribute.data.status;
					//0-新建 3-部署成功 6-部署失败 8-删除失败9-部署中,10没有部署
					this.$set(environ,'deployStatus',vmStatus)
					this.$set(environ,'projectId',projectId)
					if(projectId && vmStatus !='9' && vmStatus !='3'){
                       this.getProjectInfo(environ);
                    }else{
                    	this.$set(environ,'errorMessage','');
                    }
				})
			},
			//获取工程部署错误详情
            getProjectInfo(project){
        		getstatusbyprjid(project.projectId).then(data => {
					if(data.code == 1){
						let projectInfo = data.attribute.project;
						let errorMessage = data.attribute.project.errorMessage;
						this.$set(project,'errorMessage',errorMessage);
					}
				}).catch(error => {
					console.log(error)
				})
			},
			intervalFunction(){
				if(this.curExp){
		    		this.clearAll();
		    	}
				this.showEnvironList.forEach(environ => {
					let symbol = environ.expid + '-' + environ.userId;
					this.getEnvironInfo(environ);
					if(!this.environTime[symbol]){
						this.environTime[symbol] = setInterval(() => {
	//						console.log('Interval')
							this.getEnvironInfo(environ);
						},10000)
					}
				})
			},
			getEnvironInfo(environ){
				if((this.classInfo.type == '3' && this.classInfo.status == '0') || this.classInfo.type == '1'){ //实操模式 或者 教学模式的实操状态 ,获取学员登录信息
					this.getDeployStatus(environ); //没有部署成功，获取部署状态
					if(environ.deployStatus == 3){ //如果部署成功，获取登录信息
						this.getAccessRecord(environ);
					}else{
						environ.loginText = '未接入虚拟机';
						environ.login = false;
						//this.getDeployStatus(environ); //没有部署成功，获取部署状态
					}
				}else{ //讲课模式 或者 教学模式的讲课状态，获取学员查看投屏信息
					if(environ.type == 'T'){ //获取教师登陆信息，工程状态
						this.getDeployStatus(environ);
						if(environ.deployStatus == 3){
							this.getAccessRecord(environ);
						}else{
							//this.getDeployStatus(environ); //没有部署成功，获取部署状态
							environ.loginText = '未接入虚拟机';
							environ.login = false;
						}
					}else{
						if(this.classInfo.type == '3'){ //教学模式,学生
							this.getDeployStatus(environ);
							if(environ.deployStatus == 3){
								this.queryCheckScreenStatus(environ);
							}else{
								this.queryCheckScreenStatus(environ);
								//this.getDeployStatus(environ); //没有部署成功，获取部署状态
							}
						}else{
							this.queryCheckScreenStatus(environ);
						}
					}
				}
				//查询学员在线状态
				this.getCompanyUsersInfo(environ);
			},
			enterEnviron(projectId){
				let routeData = this.$router.resolve({path: `/environment/${projectId}/${this.curExpId}`});
  				window.openTrain(routeData.href, '_blank');
			},
			doExperimentDestroy(exp) {
				this.$set(exp,'disDestory',true)
				let paramas ={
					projectId: exp.projectId,
					userId: exp.userId
			    };
				experimentDestroy(paramas).then(data=>{
				  if(data.code ==1){
					this.$Message.success('操作成功');
					this.$set(exp,'disDestory',false)
					this.getDeployStatus(exp);
				  }else{
					_this.$Message.error(data.message)
				  }
				}).catch(error=>{
        			_this.$Message.error(error)
      			})
			},
			batchExperimentDestroy(){
				this.batchDestroyLoading = true;
				const msg = this.$Message.loading({
                    content: '请求中...',
                    duration: 0
                });
				let params = this.selectOpUsers.filter(environ => environ.projectId).map(environ => {
					return {
						projectId: environ.projectId,
						userId: environ.userId
					}
				})
				batchExperimentDestroy(params).then(data=>{
				  if(data.code ==1){
				  	setTimeout(msg,20);
				  	setTimeout(() => {
				  		this.$Message.success('操作成功');
				  	},20)
					this.selectOpUsers = [];
					this.showEnvironList.forEach(environ => {
		    			this.getDeployStatus(environ);
		    		})
					this.batchDestroyLoading = false;
				  }else{
				  	setTimeout(msg,20);
					setTimeout(() => {
				  		this.$Message.error(data.message);
				  	},20)
					this.batchDestroyLoading = false;
				  }
				}).catch(error=>{
        			setTimeout(msg,20);
					setTimeout(() => {
				  		this.$Message.error('请求失败');
				  	},20)
					this.batchDestroyLoading = false;
      			})
			},
			getVms(projectId){
				getVms(projectId).then(data => {
					if(data.code == 1){
						this.vmsList = data.attribute.vms;
						this.getCPUData();
						this.getVmStatus(data.attribute.vms.map(device => device.id));
					}else{
						this.vmsList = [];
					}
				})
			},
			getVmStatus(vms){
				clearTimeout(this.vmStatusTimeout);
                if(vms.length <= 0 ){
                    return;
                }
                queryVmStatus(vms).then( res => {
                        if(res.code == 1 && res.attribute){
                            this.vmsList.forEach(host => {
                                res.list.forEach(vm =>{
                                    if(host.id == vm.vmId){
                                        this.$set(host,'status',vm.status);
                                        return;
                                    }
                                })
                            })
                            this.vmStatusTimeout = setTimeout(() => {
                            	this.getVmStatus(vms);
                            },3000)
                        }
                    })
                    .catch( error =>  {
                        // Alert("danger",error);
                    })
            },
            cancelTimeout(){
            	clearTimeout(this.vmStatusTimeout);
            },
			updateClassStatus(status){
		    	updateClassStatus(this.curClass.id,status).then(data => {
		    		if(data.code == 1){
		    			this.$Message.info('操作成功')
		    		}else{
		    			this.$Message.warning(data.message)
		    		}
		    	})
		    },
		    rowClassName (row, index) {
                if (row.type === "T") {
                    return 'demo-table-info-row';
                }
                return '';
           },
           changeEnvironPage(page){
           	    this.environPage = page;
           },
           disDeploy(environ){
//         	  console.log(this.disbledAllBtn);
           	  let status1 = this.classInfo.type == '2' && environ.type == 'S'; //讲课模式的学生,不需要部署
           	  //6：部署失败  10：未部署   / 部署状态为undefined /部署状态为0，但是有错误信息
           	  if(!this.disbledAllBtn && !environ.disDeploy && !status1 && this.courseStatus != 3 && ((environ.deployStatus == 6) || (environ.deployStatus == 10) || (!environ.deployStatus) || (environ.deployStatus === 0  && environ.errorMessage))){
           	  	return false
           	  }else{
           	  	return true
           	  }
           	  //((params.row.deployStatus == 6 && !status1) || (params.row.deployStatus == 10 && !status1) || (!params.row.deployStatus && params.row.deployStatus != 0 && !status1)) ? false : true
           },
           //操作虚拟机
            opVm(id,action){
            	opVms(id,action).then(data => {
            		if(data.code == 1){
            			this.$Message.info('操作成功')
            			this.getVms(this.curProjectId);
            		}else{
            			this.$Message.error(data.message)
            		}
            	}).catch(error =>{
            		this.$Message.error('操作失败')
            	})
            },
            //重置虚拟机
            rebuildVm(id){
            	rebuildVm(id).then(data => {
            		if(data.code == 1){
            			this.$Message.info('操作成功');
            			this.getVms(this.curProjectId);
            		}else{
            			this.$Message.error(data.message)
            		}
            	}).catch(error =>{
            		this.$Message.error('操作失败')
            	})
            },
            //重启虚拟机
            rebootVm(id,type){
            	rebootVm(id,type).then(data => {
            		if(data.code == 1){
            			this.$Message.info('操作成功')
            			this.getVms(this.curProjectId);
            		}else{
            			this.$Message.error(data.message)
            		}
            	}).catch(error =>{
            		this.$Message.error('操作失败')
            	})
            },
            clearTimeout(){
            	clearTimeout(this.timeout);
            },
            getCPUData(host){
                this.clearTimeout();
                let index = 0;
                this.vmsList.forEach(host => {
                    if(!host.instanceName){
                        return;
                    }
                    getmemdata({vmId:host.id})
                    .then( data =>  {
                        if(data.code == 1){
                            index ++ ;
                            let response = data.data;
                            if(response.cpuUsage){
                                this.$set(host,'cpuRate',response.cpuUsage + '%');
                                this.$set(host,'cpuVal',response.cpuUsage);
                            }else{
                                this.$set(host,'cpuRate','0%');
                                this.$set(host,'cpuVal',0);
                            }
                            if(response.diskUsage){
                                this.$set(host,'diskRate',response.diskUsage + '%');
                                this.$set(host,'diskVal',response.diskUsage);
                            }else{
                                this.$set(host,'diskRate','0%');
                                this.$set(host,'diskVal',0);
                            }
                            if(response.memoryUsage){
                                this.$set(host,'memRate',response.memoryUsage + '%');
                                this.$set(host,'memVal',response.memoryUsage);
                            }else{
                                this.$set(host,'memRate','0%');
                                this.$set(host,'memVal',0);
                            }
//                          if(response.netIncomingBytes){
//                              this.$set(host,'traffic',(response.netIncomingBytes +"/" +response.netOutgoingBytes));
//                          }else{
//                              this.$set(host,'traffic',"0.00/0.00");
//                          }
                            if(index ==  this.vmsList.length &&  this.timeout && this.vmsModal){
                                this.timeout = setTimeout(() => {
                                    this.getCPUData(host);
                                },5000)
                            }
                        }else{
                            Alert('info',response.error)
                        }
                    })
                    .catch( error => {
                        // Alert('danger',error.statusText)
                    })
                })
            },
            gotoTopo(scene){
	        	if(scene.projectId && scene.deployStatus != 10){
            		window.openTrain(`/jjzzTopo/index.html#/ProjectViews?projectId=${scene.projectId}`);
            	}else{
            		this.$Message.warning('工程不存在！');
            	}
	        },
	        // 选择题目并添加
	        addDeployUser(selection,row){
	        	if(!row){ // 全选
	        		selection.forEach(user => {
	        			let selQuesIds = this.selectOpUsers.map(user => user.userId);
	        			if(!selQuesIds.includes(user.userId)){ // 添加不包含的题目
	        				let environ = this.showEnvironList.find(environ => environ.userId == user.userId);
	        				if(environ){
	        					environ._checked = true;
	        				}
	        				this.selectOpUsers.push(user)
	        			}
	        		})
	        	}else{
	        		let environ = this.showEnvironList.find(environ => environ.userId == row.userId);
    				if(environ){
    					environ._checked = true;
    				}
    				this.selectOpUsers.push(row)
	        	}
	        },
            // 删除选中的题目
	        removeDeployUser(selection,row){
	        	if(!row){//全选
	        		this.showEnvironList.forEach(environ => {
	        			environ._checked = false;
	        			this.handleClose(environ.userId);
	        		})
	        	}else{
	        		let environ = this.showEnvironList.find(environ => environ.userId == row.userId);
    				if(environ){
    					environ._checked = false;
    				}
    				this.handleClose(row.userId);
	        	}
	        },
	        handleClose(userId){
	        	let index = this.selectOpUsers.findIndex(environ => environ.userId == userId);
	        	this.selectOpUsers.splice(index, 1)
	        },
	        disDestory(environ){
	        	return !this.disbledAllBtn && (environ.deployStatus == 3 && !environ.disDestory) ? false : true;
	        },
	        disSelect(environ){
	        	if(this.step === 0){
	        		return this.disDeploy(environ);
	        	}else{
	        		return this.disDestory(environ);
	        	}
	        }
		}
	}
</script>

<style>
	.ivu-table .demo-table-info-row td{
        background-color: #fff7e6;
        /*color: #ff9900;
        font-weight: bold;*/
    }
    #selectBtn{
    	margin-right:5px;
    	display: inline-block;
    }
    #selectBtn .ivu-select-selection{
    	border-radius: 0 4px 4px 0;
    }
    #selectBtn .ivu-select-arrow {
    	right:4px;
    }
    #selectBtn .ivu-select-selected-value{
    	display:none;
    }
</style>
